package org.model.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.WebSocket;
import org.model.pojo.RoleContent;

import java.util.*;

import static org.model.conf.BigModelConf.appid;
import static org.model.service.modelListener.historyList;

public class sendMsg {

//    public static List<RoleContent> historyList=new ArrayList<>(); // 对话历史存储集合


    private WebSocket webSocket;

    private String userID;

    public sendMsg(WebSocket webSocket,String userID) {
        this.webSocket = webSocket;
        this.userID=userID;
    }

    public void sendToModel(String userMessage){
        JSONObject requestJson=new JSONObject();

        JSONObject header=new JSONObject();  // header参数
        header.put("app_id",appid);
        header.put("uid", UUID.randomUUID().toString().substring(0, 10));

        JSONObject parameter=new JSONObject(); // parameter参数
        JSONObject chat=new JSONObject();
        chat.put("domain","generalv2");
        chat.put("temperature",0.5);
        chat.put("max_tokens",4096);
        parameter.put("chat",chat);

        JSONObject payload=new JSONObject(); // payload参数
        JSONObject message=new JSONObject();
        JSONArray text=new JSONArray();

        // 历史问题获取

         if(historyList.containsKey(userID)){
             if(historyList.get(userID).size()>0){
                 for(RoleContent tempRoleContent:historyList.get(userID)){
                     text.add(JSON.toJSON(tempRoleContent));
                 }
             }
         }else {
             historyList.put(userID, new ArrayList<>());
         }


        if(historyList.containsKey(userID)){
            // 最新问题
            RoleContent roleContent=new RoleContent();
            roleContent.role="user";
            roleContent.content=userMessage;
            text.add(JSON.toJSON(roleContent));

            historyList.get(userID).add(roleContent);

        }



        message.put("text",text);
        payload.put("message",message);


        requestJson.put("header",header);
        requestJson.put("parameter",parameter);
        requestJson.put("payload",payload);
         System.err.println(requestJson); // 可以打印看每次的传参明细
        boolean send = webSocket.send(requestJson.toString());
        System.out.println(send);

    }


}
